package com.stars.easyms.alarm.client.wechat;

import com.alibaba.fastjson.JSON;
import com.stars.easyms.alarm.client.BaseEasyMsAlarmClient;
import com.stars.easyms.alarm.client.EasyMsAlarmChannel;
import com.stars.easyms.alarm.client.wechat.message.MarkdownMessage;
import com.stars.easyms.alarm.factory.AlarmRestTemplateFactory;
import com.stars.easyms.alarm.message.EasyMsAlarmMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;

import java.util.Map;
import java.util.stream.Stream;

/**
 * <p>className: EasyMsWeChatAlarmClient</p>
 * <p>description: EasyMs企业微信告警客户端</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/26 2:21 下午
 */
@Slf4j
public class EasyMsWeChatAlarmClient extends BaseEasyMsAlarmClient {

    private String[] postUrls;

    EasyMsWeChatAlarmClient(EasyMsAlarmChannel easyMsAlarmChannel, String postUrl) {
        this(easyMsAlarmChannel, null, postUrl);
    }

    EasyMsWeChatAlarmClient(EasyMsAlarmChannel easyMsAlarmChannel, String id, String postUrl) {
        super(easyMsAlarmChannel, id);
        this.postUrls = Stream.of(postUrl.split(",")).map(String::trim).toArray(value -> new String[0]);
    }

    @Override
    public void sendAlarmMessage(EasyMsAlarmMessage easyMsAlarmMessage) {
        for (String postUrl : postUrls) {
            Map<String, Object> requestData = this.getMarkdownMessage(easyMsAlarmMessage.getContext());
            ResponseEntity<Object> response = AlarmRestTemplateFactory.getRestTemplate().postForEntity(postUrl, requestData, Object.class);
            if (log.isDebugEnabled()) {
                log.debug("EnterpriseWeChat sendMsg result：{}", JSON.toJSONString(response));
            }
        }
    }

    /**
     * 发送消息封装 markdown类型
     */
    private Map<String, Object> getMarkdownMessage(String message) {
        MarkdownMessage markdownMessage = new MarkdownMessage();
        markdownMessage.add(markdownMessage.getReferenceText(message));
        return markdownMessage.toMessageMap();
    }
}
